package com.mind.server;

import io.netty.channel.ChannelHandler;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.mind.core.db.DBService;
import com.mind.core.log.ServerStatusLog;
import com.mind.core.server.GameLoader;
import com.mind.core.server.ServerProcess;
import com.mind.core.server.ShutdownHooker;
import com.mind.core.util.NetUtil;

public class ServerManager {
	private static final Logger logger = Logger.getLogger(ServerManager.class);
	private final static ShutdownHooker hooker=new ShutdownHooker();
	private static ServerProcess process=null;
	public static void initServices(String ip,String port,String websocketPort) throws UnknownHostException{
		if(ip.equalsIgnoreCase("localhost")||ip.equalsIgnoreCase("127.0.0.1")){
			ip=NetUtil.getEth0IP();
		}
		//初始化配置文件
		ChannelHandler ioHandler=new GameIoHandler();
		process=new ServerProcess(ip, "TEST", port,websocketPort,ioHandler);
		initProcessor();
	}
	private static void initProcessor(){
		//聊天
//		NoQueueMessageProcessor chatProcessor=new NoQueueMessageProcessor();
//		processorDispatcher.registerMessageProcessor(messageType, chatProcessor);
		//战斗
//		QueueMessageProcessor fightProcessor=new QueueMessageProcessor();
//		MessageProcessorDispatcher.getInstance().registerMessageProcessor(null, fightProcessor);
	}
	
	
	public static void startServices() throws Exception{
		// 停机时停止主线程的处理
		hooker.register(new Runnable() {
			@Override
			public void run() {
				process.stop();
				//数据库处理服务
				DBService.getInstance().stop();
				logger.info("正在关闭服务");
			}
		});
		// 增加JVM停机时的处理
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				try {
					ServerStatusLog.getDefaultLog().logStoppping();
					hooker.run();
				} finally {
					ServerStatusLog.getDefaultLog().logStopped();
				}
			}
		});
		// 启动各项服务
		process.start();
		//启动数据库处理服务
		//DBService.getInstance().start();
		//注册消息服务
		GameLoader.getInstance().dealCodec();
	}

}
